#include <iostream>
#include <string>
#include <sstream>
#include <memory>
#include <jsoncpp/json/json.h>

bool Serialize(const Json::Value & val,std::string & body)
{
    std::stringstream ss;
    //实例化工厂
    Json::StreamWriterBuilder swb;
    swb["emitUTF8"] = true;

    std::unique_ptr<Json::StreamWriter> sw(swb.newStreamWriter());
    int ret = sw->write(val,&ss);
    if(ret != 0)
    {
        std::cout<<"write fail"<<std::endl;
        return false;
    }
    body = ss.str();
    return true;
}

bool DeSerialize(const std::string & body,Json::Value &val)
{
    Json::CharReaderBuilder crb;
    std::string errs;
    std::unique_ptr<Json::CharReader> cr(crb.newCharReader());
    bool ret = cr->parse(body.c_str(),body.c_str()+body.size(),&val,&errs);
       if (ret == false) {
        std::cout << "json unserialize failed : " << errs << std::endl;
        return false;
    }
    return true;

}
int main()
{
    const char* name = "张三";
    int age  = 18;
    const char* gender = "男";
    float score[3] = {78.1,99,88.3};
    Json::Value student;
    student["name"] = name;
    student["age"] = age;
    student["sex"] = gender;
    student["score"].append(score[0]);
    student["score"].append(score[1]);
    student["score"].append(score[2]);
    Json::Value fav;
    fav["book"] = "西游记";
    fav["sports"] = "pingpang";
    student["fav"] = fav;

    std::string body;

    Serialize(student,body);
    std::cout<<body<<std::endl;


    std::string str = R"({"name":"小黑", "age": 19, "score":[32, 45, 56]})";
    Json::Value stu;
    bool ret = DeSerialize(str, stu);
    if (ret == false) 
        return -1;
    std::cout << "姓名: " <<  stu["name"].asString() << std::endl;
    std::cout << "年龄: " <<  stu["age"].asInt() << std::endl;
    int sz = stu["score"].size();
    for (int i = 0; i < sz; i++) {
        std::cout << "成绩: " <<  stu["score"][i].asFloat() << std::endl;
    }
}